<?php 
/* $Id$ */
/**
 * @package SwfUploadComponent
 * @subpackage controllers.components
 */
class RelatedPageUtilComponent extends Object {
    var $name = 'RelatedPageUtilComponent';
    
    /**
     * Contructor function
     * @param Object &$controller pointer to calling controller
     */
    function startup(&$controller) {
        // initialize members
        $this->uploadpath = 'files' . DS . 'uploads' . DS;

        //keep tabs on mr. controller's params
        $this->params = $controller->params;
		
        $this->controller = $controller;
    }
    
    function paginate($id, $parentModelName, $model, $group, $fields, $options = array()) {
    	$this->controller->paginate[$model->name] = array(
			'conditions'	=>	array(
				'RelatedReference.foreign_key'	=>	$id,
				'RelatedReference.model'		=>	$parentModelName,
				'RelatedReference.group'		=>	$group
			),
			'fields'		=>	$fields,
			'joins' => array(
				array(
					'table' => $model->hasAndBelongsToMany['Category']['joinTable'],
					'type' => 'INNER',
					'alias' => 'ReferenceCategory',
					'conditions' => array(
						"{$model->name}.id = ReferenceCategory.page_id"
					)
				),
				array(
					'table' => $model->Category->table,
					'type' => 'INNER',
					'alias' => 'Category',
					'conditions' => array(
						"Category.id = ReferenceCategory.category_id"
					)
				),
				array(
					'table' => 'related_pages',
					'type' => 'INNER',
					'alias' => 'RelatedReference',
					'conditions' => array(
						$model->name . ".id = RelatedReference.related_page_foreign_key",
						"RelatedReference.related_page_model"	=>	$model->name
					)
				)
			),
		) + $options;
		
		$records = $this->controller->paginate($model->name);
		return $records;
    }
    
	function findAll($id, $parentModelName, $model, $group, $fields, $options = array()) {
    	$query = array(
			'conditions'	=>	array(
				'RelatedReference.foreign_key'	=>	$id,
				'RelatedReference.model'		=>	$parentModelName,
				'RelatedReference.group'		=>	$group
			),
			'fields'		=>	$fields,
			'joins' => array(
				array(
					'table' => $model->hasAndBelongsToMany['Category']['joinTable'],
					'type' => 'INNER',
					'alias' => 'ReferenceCategory',
					'conditions' => array(
						"{$model->name}.id = ReferenceCategory.page_id"
					)
				),
				array(
					'table' => $model->Category->table,
					'type' => 'INNER',
					'alias' => 'Category',
					'conditions' => array(
						"Category.id = ReferenceCategory.category_id"
					)
				),
				array(
					'table' => 'related_pages',
					'type' => 'INNER',
					'alias' => 'RelatedReference',
					'conditions' => array(
						$model->name . ".id = RelatedReference.related_page_foreign_key",
						"RelatedReference.related_page_model"	=>	$model->name
					)
				)
			),
		) + $options;
		
		$records = $model->find('all', $query);
		return $records;
    }
}
?>